<?php
	/**********************
	created by: Moses Chan
	created on: 08-11-12
		edited on: 15-11-12: adds password field into Customers table in database
								stores the user password into database
		
	todo: check database to see if user supplied email is already in database or not
	
	**********************/


	function insertCustomer($cusInfo){
		
		$dbHost = 'localhost';
		//$dbPort = '8889';
		$dbUser = 'root';
		$dbPass = 'root';
		$dbSelect = 'TravelExperts';
		$dbh = new mysqli($dbHost, $dbUser, $dbPass, $dbSelect);
		if(!$dbh) {die();}
		//else {echo "Connected to db server/n/n";}
		
		//make sure there is a password field in the customers table of the database
		if(!$dbh->query("ALTER TABLE Customers ADD Password VARCHAR(32);"))
			//{echo 'failed to add password column into database table Customers';}
		
		$sqlColNames = '';
		$sqlValues = '';
		
		$cusInfo['Password'] = md5($cusInfo['Password']);
		$cusInfo['pwd2'] = md5($cusInfo['pwd2']);
		
		//iterate through $_POST array and get user input
		foreach($cusInfo as $key => $value) {
			//we only care about the fields that start with "Cust"
			if((preg_match("/^Cust/", $key) === 1) || (preg_match("/^Password$/", $key) === 1)) {
				$sqlColNames .= "$key,";
				$sqlValues .= "'$value',";
			}
		}
				
		//trim the last ', '
		$sqlColNames = rtrim($sqlColNames, ", ");
		$sqlValues = rtrim($sqlValues, ", ");
		//build the sql INSERT statement
		$sql = "INSERT INTO Customers ($sqlColNames) VALUES ($sqlValues)";
		$sqlQuery = $sql;
		//echo "SQL statement:\n".$sql."/n/n";
		if($dbh->query($sql)) {$sqlStatus = 'Successfully inserted data to database!';}
		else {$sqlStatus = "Insert operation failed: ".$dbh->connect_error;}
		//echo $sqlStatus;
		
		//close the db connection
		$dbh->close();
		return array('query' => $sql, 'status' => $sqlStatus);
		
		//to-do: put the user/password into the users.txt file
		}
		

		
	if(isset($_POST['infoValid'])) {
		if($_POST['infoValid'] == "t") {
			$sqlStuff = insertCustomer($_POST);
			if(!isset($_SESSION['newCustPurch'])) {
				include("gpagetop.php");
				echo 'Welcome '.$_POST['CustFirstName'].'!<br/>';
				echo 'You have successfully created an account with Travel Experts.<br/>';
				include("gpagebottom.php");
			}
			else {header("Location: confirmation.php");}
			
		}
		else {header("Location: custreg.php");}
	}
	else {header("Location: custreg.php");}

?>